package com.clg.common.jdbc;

import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
import java.sql.Connection;
import java.sql.Driver;
import java.sql.SQLException;

/**
 * Created by usercai on 2016/10/15.
 */
public class DatabaseKit {
    public static Connection getConnection(String jdbcUrl,String className,String user,String pass,String jarPath){
        Connection connection = null;
        URLClassLoader urlClassLoader = null;
        try {
            urlClassLoader = new URLClassLoader(new URL[]{new File(jarPath).toURI().toURL()},Thread.currentThread().getContextClassLoader());
        } catch (MalformedURLException e) {
            throw new RuntimeException("错误的路径",e);
        }
        try {
            Class<?> jClass = Class.forName(className, true, urlClassLoader);
            DriverManage.registerDriver((Driver) jClass.newInstance());
        } catch (Exception e) {
            throw new RuntimeException("jar包解析Driver错误",e);
        }

        try {
            connection = DriverManage.getConnection(jdbcUrl,user,pass);
        } catch (SQLException e) {
            throw new RuntimeException("JDBC连接失败："+e.getMessage(),e);
        }

        return connection;
    }
}
